package cn.liulingfengyu.behavioralpatterns.mementopattern;

/**
 * 备忘录模式示例
 */
public class MementoPatternDemo {
    public static void main(String[] args) {
        // 创建原始对象
        Originator originator = new Originator();
        originator.setState("State #1");
        System.out.println("原始状态: " + originator.getState());

        // 创建备忘录并保存状态
        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(originator.createMemento());

        // 改变原始对象的状态
        originator.setState("State #2");
        System.out.println("改变后的状态: " + originator.getState());

        // 恢复原始对象的状态
        originator.restoreFromMemento(caretaker.getMemento());
        System.out.println("恢复后的状态: " + originator.getState());
    }
}

/**
 * 发起人类
 */
class Originator {
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Memento createMemento() {
        return new Memento(state);
    }

    public void restoreFromMemento(Memento memento) {
        state = memento.getState();
    }
}

/**
 * 备忘录类
 */
class Memento {
    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }
}

/**
 * 管理者类
 */
class Caretaker {
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}